package com.wstuo.common.noticeRule.service;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.util.StringUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 邮件模板Service
 * @author WSTUO
 * 
 */
public class EmailTemplateService implements IEmailTemplateService{
	private final static Logger LOGGER = Logger
			.getLogger(EmailTemplateService.class);
	static Map<String,Configuration> cfMap = new ConcurrentHashMap<String,Configuration>();
	/**
	 * 根据传入的路径返回一个Configuration
	 * 
	 * @param templateDir
	 *            String型,表示一个存在的FreeMaker模板文件全局加载时所需要加载的文件路径
	 * @return Configuration
	 * @throws IOException
	 * */
	private static Configuration getConfiguration(String templateDir,String tenantId)
			throws IOException {
		Configuration cfg =cfMap.get(tenantId);
		if (null == cfg) {// 单例,醉汉式
			cfg = new Configuration();
			File templateDirFile = new File(templateDir);
			cfg.setDirectoryForTemplateLoading(templateDirFile);

			cfg.setLocale(Locale.CHINA);
			cfg.setDefaultEncoding("UTF-8");
		}
		return cfg;
	}

	/**
	 * 根据传入的模板和数据,生成可用数据
	 * 
	 * @param templateFileDir
	 *            String型,表示一个存在的FreeMaker模板文件全局加载时所需要加载的文件路径
	 * @param templateFile
	 *            取得模板的名字
	 * @param data
	 *            Object型,为模版中的插值提供数据
	 * @return StringBuffer
	 * */
	public static StringBuffer getTemplateStr(String templateFileDir,
			String templateFile, Object data,String tenantId) {
		StringBuffer result = null;
		StringWriter sw =null;
		try {
			Template template = getConfiguration(templateFileDir,tenantId).getTemplate(
					templateFile);
			sw = new StringWriter();
			template.process(data, sw);
			result = sw.getBuffer();
		} catch (IOException e) {
			LOGGER.error(e);
		} catch (TemplateException temp) {
			LOGGER.error(temp);
		} finally {
			try {
				if(sw!=null){
					sw.flush();
					sw.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);
			}
			
		}
		return result;
	}

	/**
	 * 调用FreeMarker 模板生成内容
	 * @param object 为模板提供数据
	 * @param templateFileDir 指定模板
	 * @param templateFile
	 * @return 生成的内容
	 */
	@Transactional
	public String template(Object object, String templateFileDir,
			String templateFile,String tenantId) {
		StringBuffer sb = getTemplateStr(templateFileDir, templateFile, object,tenantId);
		String str = changeUTF8Space(sb.toString());
		return str;
	}
	
	//空格转码
	private String changeUTF8Space(String currentStr){
		try {
			byte bytes[] = {(byte) 0xC2,(byte) 0xA0};
	        String utfSpace = new String(bytes,"UTF-8");
			currentStr = currentStr.replaceAll(utfSpace, "&nbsp;");
		} catch (UnsupportedEncodingException e) {
			LOGGER.error(e);
		}
        return currentStr;
    }
	
	/**
	 * 从基础数据的邮件模板文件复制到租户下的模板文件
	 * @param destDir
	 */
	public void copyEmailTemplate(String destDir){
		  try {
			  if(StringUtils.hasText(destDir)){
					String sourcePath = Thread.currentThread()
							.getContextClassLoader().getResource("").getPath()+IEmailTemplateService.TEMPLATEDIRNAME;
				  FileUtils.copyDirectory(new File(sourcePath),new File(destDir));
			  }
		} catch (IOException e) {
			LOGGER.error(e);
		}
	  }
}
